import 'package:grpc/grpc.dart';
import 'package:grpc_demo/src/generated/grpc_demo.pbgrpc.dart';

Future<void> main(List<String> args) async {
  final channel = ClientChannel(
    'localhost',
    port: 50051,
    options: const ChannelOptions(
        credentials: ChannelCredentials.insecure(),
        keepAlive: ClientKeepAliveOptions(permitWithoutCalls: true)),
  );
  final stub = SearchServiceClient(channel);

  final name = args.isNotEmpty ? args[0] : 'world';

  try {
    var result = <SearchRequest_Result>[SearchRequest_Result(title: "百度")];
    var searchRequest = SearchRequest(results: result);
    var response = await stub.search(searchRequest);
    print('response: $response');

    var result1 = <SearchRequest_Result>[SearchRequest_Result(title: "百度")];
    var searchRequest1 = SearchRequest(results: result1);
    var response1 = stub.search1(searchRequest1);
    print('response response1: $response1');
    await for (var feature in response1) {
      print('response response1: $feature');
      print('---------------------');
    }
    Stream<SearchRequest> createStream({int count = 5}) async* {
      for (int i = 0; i < count; i++) {
        await Future.delayed(const Duration(seconds: 1));
        var result1 = <SearchRequest_Result>[
          SearchRequest_Result(title: "百度$i")
        ];
        yield SearchRequest(results: result1);
      }
    }

    // var result2 =  Stream.periodic(const Duration(seconds: 1),(counter){
    //   var result1 = <SearchRequest_Result>[SearchRequest_Result(title: "百度$counter")];
    //   return SearchRequest(results: result1);
    // }).take(5);
    var response2 = await stub.search2(createStream(count: 10));
    print('response response2: $response2');

    Stream<SearchRequest> createStream1({int count = 5}) async* {
      for (int i = 0; i < count; i++) {
        await Future.delayed(const Duration(seconds: 1));
        var result1 = <SearchRequest_Result>[
          SearchRequest_Result(title: "腾讯$i")
        ];
        yield SearchRequest(results: result1);
      }
    }

    var response3 = await stub.search3(createStream1(count: 10));

    await for (var feature in response3) {
      print('response response3: $feature');
      print('---------------------');
    }
  } catch (e) {
    print('Caught error: $e');
  }
  await channel.shutdown();
}
